﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using Urs.Admin.Models.Orders;
using Urs.Core;
using Urs.Data.Domain.Orders;
using Urs.Services.Users;
using Urs.Services.Localization;
using Urs.Services.Logging;
using Urs.Services.Media;
using Urs.Services.Orders;
using Urs.Services.Security;
using Urs.Framework.Controllers;
using Urs.Framework.Kendoui;
using Urs.Web.Infrastructure;

namespace Urs.Admin.Controllers
{
    [AdminAuthorize]
    public partial class AfterSalesController : BaseAdminController
    {
        #region Fields

        private readonly IOrderService _orderService;
        private readonly IPictureService _pictureService;
        private readonly IUserService _userService;
        private readonly ILocalizationService _localizationService;
        private readonly IWorkContext _workContext;
        private readonly IActivityLogService _activityLogService;
        private readonly IPermissionService _permissionService;

        #endregion Fields

        #region Constructors

        public AfterSalesController(IOrderService orderService,
            IPictureService pictureService,
            IUserService userService,
            ILocalizationService localizationService, IWorkContext workContext,
            IActivityLogService activityLogService, IPermissionService permissionService)
        {
            this._orderService = orderService;
            this._userService = userService;
            this._pictureService = pictureService;
            this._localizationService = localizationService;
            this._workContext = workContext;
            this._activityLogService = activityLogService;
            this._permissionService = permissionService;
        }

        #endregion

        #region Utilities

        [NonAction]
        protected bool PrepareAfterSalesModel(AfterSalesModel model,
            AfterSales returnRequest, bool excludeProperties)
        {
            if (model == null)
                throw new ArgumentNullException("model");

            if (returnRequest == null)
                throw new ArgumentNullException("returnRequest");

            var order = _orderService.GetOrderById(returnRequest.OrderId);

            var opv = _orderService.GetOrderGoodsById(returnRequest.OrderItemId);
            if (opv == null && order == null)
                return false;

            model.Id = returnRequest.Id;
            if (opv != null)
            {
                model.GoodsId = opv.GoodsId;
                model.GoodsName = opv.GoodsName;
            }
            model.OrderId = returnRequest.OrderId;
            model.UserId = returnRequest.UserId;
            model.UserName = _userService.GetUserById(returnRequest.UserId)?.Nickname;
            model.Quantity = returnRequest.Quantity;
            model.AfterSalesStatusStr = returnRequest.AfterSalesStatus.GetLocalizedEnum(_localizationService);
            model.CreateTime = returnRequest.CreateTime;

            if (!string.IsNullOrEmpty(returnRequest.Images))
            {
                var images = returnRequest.Images.Split(',');
                foreach (var item in images)
                {
                    var pictureId = 0;
                    if (int.TryParse(item, out pictureId) && pictureId > 0)
                    {
                        var picture = _pictureService.GetPictureById(pictureId);
                        if (picture != null)
                        {
                            var image = _pictureService.GetPictureUrl(picture);
                            var thumbImage = _pictureService.GetPictureUrl(picture, 100);
                            model.ThumbnailImages.Add(image, thumbImage);
                        }
                    }
                }
            }
            if (!excludeProperties)
            {
                model.ReasonForReturn = returnRequest.ReasonForReturn;
                model.RequestedAction = returnRequest.RequestedAction;
                model.UserComments = returnRequest.UserComments;
                model.StaffNotes = returnRequest.StaffNotes;
                model.AfterSalesStatusId = returnRequest.AfterSalesStatusId;
            }
            //model is successfully prepared
            return true;
        }

        #endregion

        #region Methods

        //list
        public IActionResult Index()
        {
            return RedirectToAction("List");
        }

        public IActionResult List()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageAfterSales))
                return HttpUnauthorized();

            return View();
        }

        [HttpPost]
        public IActionResult ListJson(PageRequest command)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageAfterSales))
                return HttpUnauthorized();

            var returnRequests = _orderService.SearchAfterSales(0, 0, null, command.Page - 1, command.Limit);
            var returnRequestModels = new List<AfterSalesModel>();
            foreach (var rr in returnRequests)
            {
                var m = new AfterSalesModel();
                if (PrepareAfterSalesModel(m, rr, false))
                    returnRequestModels.Add(m);
            }
            var result = new ResponseResult
            {
                data = returnRequestModels,
                count = returnRequests.TotalCount,
            };
            return Json(result);
        }

        //edit
        public IActionResult Edit(int id)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageAfterSales))
                return HttpUnauthorized();

            var returnRequest = _orderService.GetAfterSalesById(id);
            if (returnRequest == null)
                //No return request found with the specified id
                return RedirectToAction("List");

            var model = new AfterSalesModel();
            PrepareAfterSalesModel(model, returnRequest, false);
            return View(model);
        }

        [HttpPost]
        public IActionResult Edit(AfterSalesModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageAfterSales))
                return HttpUnauthorized();

            var returnRequest = _orderService.GetAfterSalesById(model.Id);
            if (returnRequest == null)
                return Json(new { error = 1 });

            if (ModelState.IsValid)
            {
                returnRequest.ReasonForReturn = model.ReasonForReturn;
                returnRequest.RequestedAction = model.RequestedAction;
                returnRequest.UserComments = model.UserComments;
                returnRequest.StaffNotes = model.StaffNotes;
                returnRequest.AfterSalesStatusId = model.AfterSalesStatusId;
                returnRequest.UpdateTime = DateTime.Now;
                _orderService.UpdateAfterSales(returnRequest);

                //activity log
                _activityLogService.InsertActivity("EditAfterSales", _localizationService.GetResource("ActivityLog.EditAfterSales"), returnRequest.Id);

                return Json(new { success = 1 });
            }

            return Json(new { error = 1, msg = ModelState.FirstMessage() });
        }

        //delete
        [HttpPost]
        public IActionResult Delete(int id)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageAfterSales))
                return HttpUnauthorized();

            var returnRequest = _orderService.GetAfterSalesById(id);
            if (returnRequest == null)
                return Json(new { error = 1 });

            _orderService.DeleteAfterSales(returnRequest);

            //activity log
            _activityLogService.InsertActivity("DeleteAfterSales", _localizationService.GetResource("ActivityLog.DeleteAfterSales"), returnRequest.Id);

            return Json(new { success = 1 });
        }

        #endregion
    }
}
